package com.andrew.interceptor;

import cn.hutool.json.JSONUtil;
import com.andrew.common.ResponseCode;
import com.andrew.common.ReturnResult;
import com.andrew.exception.ServiceException;
import com.andrew.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 拦截处理器：主要的功能是拦截扫描到 AutoIdempotent 到注解到方法,
 * 然后调用 TokenService 的 checkToken() 方法校验 token 是否正确，如果捕捉到异常就将异常信息渲染成 json 返回给前端
 */
@Component
public class AutoIdempotentInterceptor implements HandlerInterceptor {
    private Logger Logger = LoggerFactory.getLogger(AutoIdempotentInterceptor.class);

    @Autowired
    private TokenService tokenService;

    /**
     * 预处理
     *在请求处理之前进行调用(Controller方法调用之前)
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //被ApiIdempotment标记的扫描
        AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
        if (methodAnnotation != null) {
            try {
                return tokenService.checkToken(request);// 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
            }catch (ServiceException ex){
                ReturnResult<Object> objectReturnResult = ReturnResult.withNormal(ex.getCode(), ex.getMsg());
                writeReturnJson(response, JSONUtil.toJsonStr(objectReturnResult));
                throw ex;
            }
        }
        //必须返回true,否则会被拦截一切请求
        return true;
    }


    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     *  整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 返回的json值
     * @param response
     * @param content
     * @throws Exception
     */
    private void writeReturnJson(HttpServletResponse response, String content){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        // response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            // writer.write(content);
            writer.print(content);
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
